package com.lx.forum.controller;

import com.lx.forum.common.AppResult;
import com.lx.forum.common.ResultCode;
import com.lx.forum.config.AppConfig;
import com.lx.forum.dao.UserMapper;
import com.lx.forum.model.User;
import com.lx.forum.services.IUserService;
import com.lx.forum.utils.MD5Util;
import com.lx.forum.utils.UUIDUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.constraints.NotNull;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * @author 李夏
 * @version 1.0
 */
@Slf4j
@Tag(name = "用户测试接口", description = "用户测试接口")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     * 用户注册
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRepeat 确认密码
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public AppResult register(@Parameter(description = "用户名") @RequestParam("username") @NotNull String username,
                              @Parameter(description="密码")@RequestParam("password") @NotNull String password,
                              @Parameter(description="昵称")@RequestParam("nickname") @NotNull String nickname,
                              @Parameter(description="确认密码")@RequestParam("passwordRepeat") @NotNull String passwordRepeat){
       //再次输入密码
        if(!password.equals(passwordRepeat)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);

        }
        User user=new User();
        user.setNickname(nickname);
        user.setUsername(username);
        String salt= UUIDUtil.UUID_32();
        String encryptPassword= MD5Util.md5Salt(password,salt);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        userService.createNormalUser(user);
        return AppResult.success();


    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     */
    @Operation(summary = "用户登录")
    @PostMapping("/login")

    public AppResult login(HttpServletRequest request,
                           @Parameter(description="用户名")@RequestParam("username") @NotNull String username,
                           @Parameter(description="密码")@RequestParam("password") @NotNull String password){
        User user = userService.login(username, password);
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            // 返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //  如果登录成功把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();

    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @Parameter(description="用户id" )@RequestParam(name = "id",required = false) Long id){
        User user=null;
        if(id==null){
            HttpSession session = request.getSession(false);
             user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
             user= userService.selectById(id);
        }
        if(user==null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);

    }
    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){

        HttpSession session = request.getSession(false);
        // 判断session是否有效
        if(session!=null){
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }


    /**
     * 修改个人信息
     * @param username 用户名
     * @param nickname 昵称
     * @param gender 性别
     * @param email 邮箱
     * @param phoneNum 电话号
     * @param remark 个人简介
     * @return AppResult
     */
    @Operation(summary = "修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @Parameter(description="用户名") @RequestParam(value = "username",required = false) String username,
                                 @Parameter(description="昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                 @Parameter(description="性别") @RequestParam(value = "gender",required = false) Byte gender,
                                 @Parameter(description="邮箱") @RequestParam(value = "email",required = false) String email,
                                 @Parameter(description="电话号") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                 @Parameter(description="个人简介") @RequestParam(value = "remark",required = false) String remark) {
        // 1. 接收参数
        // 2. 对参数做非空校验（全部都为空，则返回错误描述）
        if (!StringUtils.hasLength(username) && !StringUtils.hasLength(nickname)
                &&! StringUtils.hasLength(email) &&! StringUtils.hasLength(phoneNum)
                &&! StringUtils.hasLength(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }

        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 3. 封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介

        // 4. 调用Service中的方法
        userService.modifyInfo(updateUser);
        // 5. 查询最新的用户信息
        user = userService.selectById(user.getId());
        // 6. 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 7. 返回结果
        return AppResult.success(user);
    }

    @Operation(summary ="修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                     @Parameter(description="原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @Parameter(description="新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @Parameter(description="确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 1. 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            // 返回错误描述
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 2. 获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 3. 调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        // 4. 销毁session
        if (session != null) {
            session.invalidate();
        }
        // 5. 返回结果
        return AppResult.success();
    }


}
